﻿//  @ Project : SPPager
//  @ File Name : StoredProcedureBase.cs
//  @ Date : 2013/6/5
//  @ Author : yubaolee(.cpp)
//  @ Description: 

using System;
using System.Data.SqlClient;
using System.Data;
namespace LYB.NET.SPPager
{
    public abstract class StoredProcedureBase
    {
        private readonly SqlConnection _conn;
        protected SqlCommand Command;
        private readonly string _storedProcedureName;

        protected int PageSize { get; set; }
        protected int CurrentPageIndex { get; set; }
        public abstract SqlParameter[] Parament { get; }
        public abstract int TotalRecordCount { get; }

        public SqlDataReader GetDataReader(int pageindex, int pagesize)
        {
            PageSize = pagesize;
            CurrentPageIndex = pageindex;

            if (Command != null)
                Command.Dispose();
            Command = BuilderQueryCommand(_storedProcedureName, Parament);

            SqlDataReader reader;
            if (_conn.State == ConnectionState.Closed)
            {
                _conn.Open();
            }
            try
            {
                reader = Command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (System.Exception ex)
            {
                throw (new ApplicationException(ex.Message));
            }
            
            return reader;
        } 

        public StoredProcedureBase(string connection, string storedProcName)
        {
            _conn = new SqlConnection(connection);
            _storedProcedureName = storedProcName;
        }

        /// <param name="storedProcName">stored procedure name</param>  
        /// <param name="parameters">parameters for sp</param>  
        private SqlCommand BuilderQueryCommand(string storedProcName, SqlParameter[] parameters)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandText = storedProcName.Trim();
            command.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            return command;
        }
    }
}
